package com.googlecode.dgwt.client.dojo.util;

import java.util.Collection;

import com.googlecode.dgwt.client.dojo.data.listener.AttachListener;
import com.googlecode.dgwt.client.dojo.exception.AttachException;

/**
 * This type of list provides functionalities to be used when coding components
 * with parent/child relationships. <br/>
 * <br/>
 * When a child object is added, replaced or removed from the list, it is
 * notified by this list calling the methods specified in {@link AttachListener}
 * interface.<br/>
 * <br/>
 * Note that <code>null</code> is not allowed and a child object can't be added
 * more than once.
 * 
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class AttachList<Parent, Child extends AttachListener<Parent>> extends SharedList<Child> {

    protected Parent parent;

    public AttachList(Parent parent, Collection<? extends Child> list) {
        super(list);
        this.parent = parent;
    }

    public AttachList(Parent parent, int capacity) {
        super(capacity);
        this.parent = parent;
    }

    public AttachList(Parent parent) {
        super();
        this.parent = parent;
    }

    
    /* (non-Javadoc)
     * @see com.googlecode.dgwt.client.dojo.util.SharedList#getParent()
     */
    @Override
    public Parent getParent() {
        return parent;
    }

    /* (non-Javadoc)
     * @see com.googlecode.dgwt.client.dojo.util.SharedList#onBeforeAdd(int, java.lang.Object)
     */
    @Override
    protected void onBeforeAdd(int index, Child item) throws AttachException {
        item.onAttach(getParent());
    }

    /* (non-Javadoc)
     * @see com.googlecode.dgwt.client.dojo.util.SharedList#onAfterRemove(int, java.lang.Object)
     */
    @Override
    protected void onAfterRemove(int index, Child item) {
        item.onDetach(getParent());
    }

    /* (non-Javadoc)
     * @see com.googlecode.dgwt.client.dojo.util.SharedList#onBeforeReplace(int, java.lang.Object, java.lang.Object)
     */
    @Override
    protected void onBeforeReplace(int index, Child oldItem, Child newItem) throws AttachException {
        newItem.onAttach(getParent());
    }

    /* (non-Javadoc)
     * @see com.googlecode.dgwt.client.dojo.util.SharedList#onAfterReplace(int, java.lang.Object, java.lang.Object)
     */
    @Override
    protected void onAfterReplace(int index, Child oldItem, Child newItem) {
        oldItem.onDetach(getParent());
    }

}
